package org.destiny.msglipse.views;

import java.io.IOException;
import java.net.URLEncoder;

import org.destiny.msglipse.Activator;
import org.destiny.msglipse.ResourceUtil;
import org.destiny.msglipse.component.MySashForm;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.ReceiverAdapter;
import org.jgroups.View;

public class MessageView extends ViewPart {
	public static final String groupName = "helloworld-001";
	public static final String myName = "sky";

	private Text inputText;
	private Button sendBtn;
	private Text viewText;
	private Action action1;
	private Action action2;
	Action doubleClickAction;
	private JChannel channel;
	private ListViewer listViewer;

	/**
	 * The ID of the view as specified by the extension.
	 */
	public static final String ID = "org.destiny.msglipse.views.MessageView";

	public MessageView() {
		try {
			initJGroups(groupName, ResourceUtil.randomName());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void createPartControl(Composite parent, boolean plugin) {
		parent.setLayout(new FillLayout());
		MySashForm sashForm = new MySashForm(parent, SWT.HORIZONTAL | SWT.FLAT);
		// sashForm.setLayout(new FillLayout());
		Composite chatPane = new Composite(sashForm, SWT.NONE);
		listViewer = new ListViewer(sashForm, SWT.NONE);
		listViewer.getControl().setSize(100, 0);
		sashForm.setLeft(chatPane);
		sashForm.setRight(listViewer.getControl());
		listViewer.setContentProvider(new GroupListContentProvider());
		listViewer.setInput(new Object());
		SelectionAdapter sendAction = new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (e.getSource() == sendBtn)
					doSendAction();
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				if (e.getSource() == inputText)
					doSendAction();
			}
		};

		viewText = new Text(chatPane, SWT.WRAP | SWT.BORDER);
		viewText.setEditable(false);
		viewText.setMenu(createTextMenu(viewText));
		inputText = new Text(chatPane, SWT.BORDER);
		inputText.addSelectionListener(sendAction);
		inputText.setMenu(createTextMenu(inputText));
		sendBtn = new Button(chatPane, SWT.PUSH);
		sendBtn.setText("send");
		sendBtn.addSelectionListener(sendAction);
		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 2;
		chatPane.setLayout(gridLayout);
		initLayoutData();
		if (plugin) {
			makeActions();
			contributeToActionBars();
		}
	}

	public void createPartControl(Composite parent) {
		createPartControl(parent, true);
	}

	public void initLayoutData() {

		GridData gridData = new GridData();
		gridData.horizontalSpan = 2;
		gridData.grabExcessVerticalSpace = true;
		// gridData.grabExcessHorizontalSpace = true;
		gridData.horizontalAlignment = SWT.FILL;
		gridData.verticalAlignment = SWT.FILL;
		viewText.setLayoutData(gridData);

		gridData = new GridData();
		gridData.grabExcessHorizontalSpace = true;
		gridData.horizontalAlignment = SWT.FILL;
		inputText.setLayoutData(gridData);

		gridData = new GridData();
		gridData.horizontalAlignment = SWT.CENTER;
		sendBtn.setLayoutData(gridData);
	}

	public void setFocus() {
		inputText.setFocus();
	}

	public Menu createTextMenu(final Text text) {
		Menu menu = new Menu(text);
		MenuItem copy = new MenuItem(menu, SWT.PUSH);
		copy.setText("复制");
		copy.setImage(ResourceUtil.getSharedImage(ISharedImages.IMG_TOOL_COPY));
		copy.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				text.copy();
			}
		});
		MenuItem paste = new MenuItem(menu, SWT.PUSH);
		paste.setText("粘贴");
		paste.setImage(ResourceUtil.getSharedImage(ISharedImages.IMG_TOOL_PASTE));
		paste.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				text.paste();
			}
		});
		MenuItem cut = new MenuItem(menu, SWT.PUSH);
		cut.setText("剪切");
		cut.setImage(ResourceUtil.getSharedImage(ISharedImages.IMG_TOOL_CUT));
		cut.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				text.cut();
			}
		});
		MenuItem selectAll = new MenuItem(menu, SWT.PUSH);
		selectAll.setText("全选");
		selectAll.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				text.selectAll();
			}
		});
		MenuItem searchItem = new MenuItem(menu, SWT.CASCADE);
		searchItem.setText("搜索");
		Menu searchMenu = new Menu(text.getShell(), SWT.DROP_DOWN);
		searchItem.setMenu(searchMenu);
		MenuItem googleItem = new MenuItem(searchMenu, SWT.PUSH);
		googleItem.setText("google");
		googleItem.setImage(ResourceUtil.getMyImage(text.getDisplay(), "google.png"));
		googleItem.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				try {
					Runtime.getRuntime().exec(
							"cmd /c start " + "https://www.google.com.hk/search?q=" + text.getSelectionText()
									+ "&ie=utf-8&oe=utf-8&aq=t");
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		});
		MenuItem baiduItem = new MenuItem(searchMenu, SWT.PUSH);
		baiduItem.setText("baidu");
		baiduItem.setImage(ResourceUtil.getMyImage(text.getDisplay(), "baidu.png"));
		baiduItem.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				try {
					Runtime.getRuntime().exec(
							"cmd /c start http://www.baidu.com/s?wd="
									+ URLEncoder.encode(text.getSelectionText(), "gbk"));
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		});

		if (!text.getEditable()) {
			cut.setEnabled(false);
			paste.setEnabled(false);
		}
		return menu;
	}

	public void doSendAction() {
		Message msg = new Message(null, null, inputText.getText());
		inputText.setText("");
		try {
			channel.send(msg);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}

	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager) {
		manager.add(action1);
		manager.add(new Separator());
		manager.add(action2);
	}

	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(action1);
		manager.add(action2);
	}

	private void makeActions() {
		action1 = new Action() {
			public void run() {
				showMessage("Action 1 executed");
			}
		};
		action1.setText("Action 1");
		action1.setToolTipText("Action 1 tooltip");
		action1.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages()
				.getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));

		action2 = new Action() {
			public void run() {
				InputDialog inputDialog = new InputDialog(viewText.getShell(), "input name", "input name:", "", null);
				inputDialog.open();
				Activator.getDefault().setName(inputDialog.getValue());
			}
		};
		action2.setText("Action 2");
		action2.setToolTipText("Action 2 tooltip");
		action2.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages()
				.getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
		doubleClickAction = new Action() {
			public void run() {
				showMessage("Double-click detected on db");
			}
		};
	}

	private void showMessage(String message) {
		MessageDialog.openInformation(viewText.getShell(), "Messaging View", message);
	}

	public void initJGroups(String groupName, String myName) throws Exception {
		initJGroups(JChannel.DEFAULT_PROTOCOL_STACK, groupName, myName);
	}

	public void initJGroups(String props, String groupName, String myName) throws Exception {

		channel = new JChannel(props);
		channel.setName(myName);
		// jChannel.setAddressGenerator(new MyAddressGenerator("liuxyz",
		// "0.0.0.0"));
		channel.connect(groupName);
		channel.setReceiver(new Receiver());
	}

	class Receiver extends ReceiverAdapter {
		@Override
		public void receive(final Message msg) {
			viewText.getDisplay().asyncExec(new Runnable() {
				@Override
				public void run() {
					viewText.append(channel.getName(msg.getSrc()) + " say:" + msg.getObject().toString() + "\n");
				}
			});
		}

		@Override
		public void viewAccepted(final View view) {
			viewText.getDisplay().asyncExec(new Runnable() {
				@Override
				public void run() {
					listViewer.refresh();
					viewText.append("new member join or level!! size:" + view.getMembers().size() + "\n");
				}
			});
		}
	}

	class GroupListContentProvider implements IStructuredContentProvider {

		@Override
		public void dispose() {

		}

		@Override
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
			viewer.refresh();
		}

		@Override
		public Object[] getElements(Object inputElement) {
			Object[] members = channel.getView().getMembers().toArray();
			return members;
		}

	}
}